import threading

# 全局变量
g_num = 0


# 对g_num进行加操作
def sum_num1():
    # 上锁
    mutex.acquire()

    for i in range(1000000):
        global g_num
        g_num += 1

    # 解锁
    mutex.release()

    print("g_num1:", g_num)


# 对g_num进行加操作
def sum_num2():
    # 上锁
    mutex.acquire()

    for i in range(1000000):
        global g_num
        g_num += 1

    # 解锁
    mutex.release()

    print("g_num2:", g_num)


if __name__ == '__main__':
    # 创建锁
    mutex = threading.Lock()
    # 创建子线程
    sum1_thread = threading.Thread(target=sum_num1)
    sum2_thread = threading.Thread(target=sum_num2)

    # 启动线程
    sum1_thread.start()
    sum2_thread.start()

"""
    # 创建锁
    mutex = threading.Lock()
    # 上锁
    mutex.acquire()
    # 解锁
    mutex.release()    
小结：
互斥锁的作⽤就是保证同⼀时刻只能有⼀个线程去操作共享数据，保
证共享数据不会出现错误问题
使⽤互斥锁的好处确保某段关键代码只能由⼀个线程从头到尾完整地
去执⾏
使⽤互斥锁会影响代码的执⾏效率，多任务改成了单任务执⾏
互斥锁如果没有使⽤好容易出现死锁的情况
"""

